﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace BenefitHelper.Sys
{
    public class Instrument
    {
        public int Id { get; set; }

        public string InstrumentId { get; set; }

        public int ExchangeId { get; set; }

        public virtual Exchange Exchange { get; set; }

        public int ProductId { get; set; }

        public virtual Product Product { get; set; }

        /// <summary>
        /// 获取所有合约品种
        /// </summary>
        /// <returns></returns>
        public List<Instrument> GetList(DB.DBManager db)
        {
            var query = from t in db.Instrument select t;
            List<Instrument> instruments = query.ToList();
            return instruments;
        }

        /// <summary>
        /// 保存合约
        /// </summary>
        /// <returns></returns>
        public int InsertIntoBenefitFromServer(string productId, string exchangeId, string instrumentid, DB.DBManager db)
        {
            Sys.Instrument instrument = new Instrument();

            var query = from t in db.Product where t.ProductId.Equals(productId) select t;
            if (query.Count() > 0)
            {
                instrument.ProductId = query.First().Id;
            }
            else
            {
                return -1;
            }

            var query2 = from t in db.Exchange where t.ExchangeId.Equals(exchangeId) select t;
            if (query2.Count() > 0)
            {
                instrument.ExchangeId = query2.First().Id;
            }
            else
            {
                return -1;
            }

            instrument.InstrumentId = instrumentid;
            db.Instrument.Add(instrument);
            db.SaveChanges();
            int id = instrument.Id;
            return id;
        }
        /// <summary>
        /// 获取分析系统里面的合约的编号
        /// </summary>
        /// <param name="Instrument"></param>
        /// <returns></returns>
        public int GetInstrumentId(string Instrument, DB.DBManager db)
        {
            int id = 1;
            var query = db.Instrument.Where(a => a.InstrumentId.Equals(Instrument));
            if (query.Count() > 0)
            {
                id = query.First().Id;
            }
            else
            {
                ("合约列表中没有所查询的合约:" + Instrument).Info();
            }
            return id;
        }
    }
}